package com.vp.org.dao.impl;

import com.vp.org.constant.Sql;
import com.vp.org.dao.AdminInfoDao;
import com.vp.org.pojo.AdminInfo;
import com.vp.org.util.JdbcUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.List;

public class AdminInfoDaoImpl extends JdbcUtil implements Sql, AdminInfoDao {

    // 登录管理员
    @Override
    public AdminInfo adminLogin(AdminInfo adminInfo) {
        try {
            return template.queryForObject(ADMININFO_ADMINLOGIN,
                    new BeanPropertyRowMapper<>(AdminInfo.class),adminInfo.getAdmin(),adminInfo.getPassword());
        } catch (EmptyResultDataAccessException e){
            return null;
        }

    }

    // 删除供货商
    // delete from admin_info where admin = ?;
    @Override
    public int deleteAdmin(AdminInfo adminInfo) {
        return template.update(ADMININFO_DELETEADMIN,adminInfo.getAdmin());
    }

    // 修改供货商
    // update admin_info set id = ?,password = ?,department = ?,name = ?,organization = ?,address = ?,phone = ?,email = ?,qq = ? where admin = ?;
    @Override
    public int updateAdmin(AdminInfo adminInfo) {
        return template.update(ADMININFO_UPDATEADMIN,adminInfo.getId(),adminInfo.getPassword(),adminInfo.getDepartment(),
                adminInfo.getName(),adminInfo.getOrganization(),adminInfo.getAddress(),adminInfo.getPhone(),
                adminInfo.getEmail(),adminInfo.getQq(),adminInfo.getAdmin());
    }

    // 货商总数
    // select count(id) from admin_info;
    @Override
    public long countAdmin() {
        return (long)template.queryForMap(ADMININFO_COUNTADMIN).get("count");
    }

    // 货商总页数
    @Override
    public int adminPage() {
        int count = (int) countAdmin();
        return count % 3 == 0 ? count / 3 : count / 3 + 1;
    }

    // 分页查询供货商
    // select * from admin_info where admin != 'gsh'order by id limit 0,3;
    @Override
    public List<AdminInfo> queryAdmin(int page) {
        return template.query(ADMININFO_QUERYADMIN,new BeanPropertyRowMapper<>(AdminInfo.class),(page-1)*3);
    }
}
